<!--
 * @Author: 极客James
 * @Motto: 求知若渴,虚心若愚
 * @Github: https://github.com/Geek-James/ddBuy
 * @掘金: https://juejin.im/user/5c4ebc72e51d4511dc7306ce
 * @LastEditTime: 2019-12-06 17:55:10
 * @Description: 商品详情页 由于是Mock数据->通过上级页面通过路由的query传值 
 * @supplement   企业开发,只需要拿到商品的id然后请求获取数据
 * @FilePath: /ddBuy-dev/src/components/goodsDetail/GoodsDetail.vue
 -->

<template>
  <div id="goodsDetail">
    <van-nav-bar title="商品详情"
                 :fixed=true
                 left-arrow
                 @click-left="onClickLeft">
    </van-nav-bar>
    <div class="goodsDetailWrapper">
      <!-- 商品图 -->
      <div class="goodsImage">
        <img :src="goodsInfo.img1"
             alt="">
      </div>
      <!-- 限时抢购  -->
      <div class="flash"
           v-show="goodsInfo.isFlash">
        <div class="flashLeft">
          <span>限时抢购</span>
          <i>抢购中</i>
        </div>
        <div class="flashRight">
          <span>距结束</span>
          <!-- 倒计时 -->
          <van-count-down :time="time"
                          class="countStyle"
                          format="HH mm ss">
            <template v-slot="timeData">
              <span class="item">{{ timeData.hours }}</span>
              <i>:</i>
              <span class="item">{{ timeData.minutes }}</span>
              <i>:</i>
              <span class="item">{{ timeData.seconds }}</span>
            </template>
          </van-count-down>
        </div>
      </div>
      <!-- 商品名称 -->
      <div class="productInfo">
        <div class="title">{{goodsInfo.name}}</div>
        <div class="subTitle">{{goodsInfo.spec}}</div>
        <span class="originPrice">{{goodsInfo.price| moneyFormat}}</span>
        <span class="price">{{this.yj}}</span>
        <span class="totalSales">已售:{{goodsInfo.rq}}</span>
        <van-divider />
         <span class="totalSales">库存:{{goodsInfo.kc}}</span>
        <div class="shippingInfo">
          <van-icon name="cluster-o" />此商品按500g/份计价,如实收少于500g将退还差价</div>
        <van-divider />
        <div class="shippingInfo">
          <van-icon name="clock-o" />最快29分钟内送达</div>
      </div>
      <!-- 规格 -->
      <div class="specifications" style=" height: 300px">
        <div class="specificationsTitle">规格 </div>
         <van-divider dashed />
        <div class="conditions">
             <div  v-for="(item1,index) in 	process_attribute" :key="index">
            <p>{{item1.name}}:</p>
            <van-radio-group @change="xx" v-model="skuselected[index]" >
                <van-radio :name="val.name" v-for="(val,index) in item1.item" :key="index">{{val.name}}</van-radio>
            </van-radio-group>
        </div>
        </div>

       
       
        <van-divider dashed />
      </div>
      <div class="showGoods">
        <img :src="goodsInfo.img1"
             alt="">
      
      </div>

      <!-- 底部商品导航    -->
      <van-goods-action :safe-area-inset-bottom=true
                        style="z-index:100">
        <van-goods-action-icon icon="cart-o"
                               :info="goodsNum"
                               @click="onClickCar" />
        <van-goods-action-button type="warning"
                                 text="加入购物车"
                                 @click="onClickAddToCar" />
      </van-goods-action>
    </div>

    <!-- 回到顶部按钮 -->
    <v-top />
  </div>
</template>

<script type="text/javascript">
import { mapState, mapMutations } from 'vuex'

export default {
  created () {
  },
  mounted () {
      this.attribute=JSON.parse(this.goodsInfo.skuatt);
      this.sku=JSON.parse(this.goodsInfo.sku);
      this.init();
     console.log(this.goodsInfo);
     console.log(this.process_attribute);
     console.log(this.process_sku)
     console.log(this.sku)
    console.log(this.attribute)
  },
  computed: {
  },
  data () {
    return {
      xz:[],
       separator: ';',
			attribute: [],
			sku:[],
			process_attribute: [],
			process_sku: [],
			// 当前选中 sku 的库存及价格区间
			stock: '',
			minprice: '',
			maxprice: '',
      // 倒计时时间设置
      time: 30 * 60 * 1000 * 100,
      // 是否是限时抢购
      isFlash: false,
      goodsInfo: this.$route.query,
      goodsImage: 'https:\/\/img.ddimg.mobi\/3f280ff77ab3d1571213379189.jpg?width=750&height=1869',
      skuselected:[],
      zfc:"",
      yj:1000000000,
      sj:[],
    }
  },
  computed: {
    ...mapState(['shopCart']),
    // 购物车商品数量
    goodsNum () {
      let num = 0;
      Object.values(this.shopCart).forEach((goods, index) => {
        num += goods.num;
      });
      if (num > 0) {
        return num;
      }
    }
  },
  components: {
   
  },
  methods: {
    ...mapMutations(['ADD_TO_CART']),
    // 返回
    onClickLeft () {
      this.$router.go(-1);
    },
    xx(){
       console.log(this.sku)
       this.zfc=this.skuselected.join(';');
      if(this.zfc.length==1)
      {
        this.zfc=this.zfc
      }
       console.log(this.zfc)
     

     this.sku.map((a)=>{
      if(a.sku==this.zfc)
      {
        this.goodsInfo.price=a.price;
        this.yj=a.originalprice;
       
          this.sj=a;
      }
     })
    },
  
 init() {
			// 对 attribute 数据进行加工，并存入 process_attribute 中
			this.attribute.map(attr => {
				let temp = {
					name: attr.name
				}
				temp.item = attr.item.map(item => {
					return {
						name: item,
						actived: false,
						disabled: false
					}
				})
				this.process_attribute.push(temp)
			})
			// 对 sku 数据进行加工，并存入 process_sku 中
			this.sku.map(v => {
				var combArr = this.arrayCombine(v.sku.split(this.separator))
				for (var j = 0; j < combArr.length; j++) {
					var key = combArr[j].join(this.separator)
					if (this.process_sku[key]) {
						// 库存累加，价格添加进数组
						this.process_sku[key].stock += v.stock
						this.process_sku[key].prices.push(v.price)
					} else {
						this.process_sku[key] = {
							stock: v.stock,
							prices: [v.price]
						}
					}
				}
			})
			// 更新数据视图
			this.process_sku = Object.assign({}, this.process_sku)
			this.skuCheck()
		},
    arrayCombine(targetArr) {
			var resultArr = []
			for (var n = 0; n <= targetArr.length; n++) {
				var flagArrs = this.getFlagArrs(targetArr.length, n)
				while (flagArrs.length) {
					var flagArr = flagArrs.shift()
					var combArr = Array(targetArr.length)
					for (var i = 0; i < targetArr.length; i++) {
						if (flagArr[i]) {
							combArr[i] = targetArr[i]
						}
					}
					resultArr.push(combArr)
				}
			}
			return resultArr
		},
    	getFlagArrs(m, n) {
			var flagArrs = [],
				flagArr = [],
				isEnd = false
			for (var i = 0; i < m; i++) {
				flagArr[i] = i < n ? 1 : 0
			}
			flagArrs.push(flagArr.concat())
			// 当n不等于0并且m大于n的时候进入
			if (n && m > n) {
				while (!isEnd) {
					var leftCnt = 0
					for (var i = 0; i < m - 1; i++) {
						if (flagArr[i] == 1 && flagArr[i + 1] == 0) {
							for (var j = 0; j < i; j++) {
								flagArr[j] = j < leftCnt ? 1 : 0
							}
							flagArr[i] = 0
							flagArr[i + 1] = 1
							var aTmp = flagArr.concat()
							flagArrs.push(aTmp)
							if (aTmp.slice(-n).join('').indexOf('0') == -1) {
								isEnd = true
							}
							break
						}
						flagArr[i] == 1 && leftCnt++
					}
				}
			}
			return flagArrs
		},
    	skuCheck() {
			let sku = []
			this.process_attribute.map(attr => {
				let name = ''
				attr.item.map(item => {
					if (item.actived) {
						name = item.name
					}
				})
				sku.push(name)
			})
			this.stock = this.process_sku[sku.join(this.separator)].stock
			this.minprice = Math.min.apply(Math, this.process_sku[sku.join(this.separator)].prices)
			this.maxprice = Math.max.apply(Math, this.process_sku[sku.join(this.separator)].prices)
		},
    // 加入购物车
    onClickAddToCar () {
      // this.attribute.map((a)=>{
      //   console.log(a)
      //   if(a.item.disabled==false)
      //   {
      //     alert(a.item.name)
      //    this.xz.push(a.item.name);
      //   }
      //   console.log(this.xz)
      // })
      console.log(this.goodsInfo)
      console.log(this.skuselected)
      this.goodsInfo.sku=JSON.stringify(this.sj) ;
      this.goodsInfo.sl=1;
       this.goodsInfo.skuatt=JSON.stringify(this.goodsInfo.skuatt)
      this.$axios
      .post("https://localhost:44308/api/app/shop/redis-add",this.goodsInfo)
      .then((a)=>{
        if(a.data>0)
        {
          alert('添加成功');
    //        this.goodsInfo.sku=JSON.parse(this.goodsInfo.sku);
    // this.goodsInfo.skuatt=JSON.parse(this.goodsInfo.skuatt);
        }
        else
        {
          alert('添加失败');
        }
      })
      // this.ADD_TO_CART(this.goodsInfo);
    },
    // 点击了购物车
    onClickCar () {
      this.$router.push({ name: 'cart' });
    }
  }
}
</script>
<style lang="less" scoped>
#goodsDetail {
  background-color: #f5f5f5;
  .goodsDetailWrapper {
    overflow: hidden;
    margin-top: 2.7rem;
    .goodsImage {
      width: 100%;
      img {
        width: 100%;
        height: 80%;
      }
    }
    .flash {
      display: flex;
      flex: 1;
      width: 100%;
      height: 2rem;
      line-height: 2rem;
      .flashLeft {
        width: 55%;
        background-color: #e25450;
        span {
          font-size: 0.8rem;
          color: #ffffff;
          padding-left: 1rem;
        }
        i {
          padding-left: 0.6rem;
          font-size: 0.5rem;
          color: #ffffff;
        }
      }
      .flashRight {
        width: 45%;
        background-color: #fcefe9;
        height: 2rem;
        line-height: 2rem;
        padding-left: 0.5rem;
        font-size: 0.5rem;
        color: #e25450;
        .countStyle {
          display: inline;
          margin-left: 0.3rem;
          .item {
            display: inline-block;
            width: 22px;
            margin-right: 5px;
            color: #fff;
            font-size: 12px;
            text-align: center;
            background-color: #e25450;
          }
          i {
            color: #e25450;
            padding-right: 0.2rem;
          }
        }
      }
    }
    .productInfo {
      background-color: white;
      padding: 0.5rem;
      .title {
        color: black;
        font-size: 0.8rem;
      }
      .subTitle {
        padding: 0.5rem 0;
        color: grey;
        font-size: 0.6rem;
      }
      .originPrice {
        color: #e25450;
        padding-right: 0.5rem;
        font-size: 0.8rem;
      }
      .price {
        color: grey;
        font-size: 0.5rem;
        text-decoration: line-through;
      }
      .totalSales {
        float: right;
        color: #e25450;
        font-size: 0.8rem;
      }
      .shippingInfo {
        font-size: 0.6rem;
        height: 0.8rem;
        color: grey;
      }
    }
    .specifications {
      width: 100%;
      background-color: white;
      margin-top: 1rem;
      padding-left: 0.5rem;
      .specificationsTitle {
        padding-top: 1rem;
        font-size: 1rem;
        color: black;
      }
      .conditions {
        font-size: 0.6rem;
        height: 1rem;
        color: grey;
        .conditionsOne {
          padding-left: 2rem;
        }
        .conditionsTwo {
          padding-left: 2.5rem;
        }
      }
    }
    .showGoods {
      width: 100%;
      img {
        width: 100%;
      }
    }
  }
}
</style>
